<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="200px">
      <el-form-item class="w-60%" :label="t('order.contract_type')" required>
        <el-select
          v-model="form.contract_type"
          :placeholder="t('order.contract_type')"
          @change="handleChangeContractType"
        >
          <el-option
            v-for="item in contractTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="w-60%" :label="t('order.customer')" required>
        <el-input v-model="form.username" clearable disabled placeholder="">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenCustomer">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="w-60%" :label="t('dealerAssetManagement.customerEmailAddress')">
        <el-input v-model="form.email" clearable disabled placeholder=" " />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('order.orderCode')">
        <el-input v-model="form.order_no" clearable :disabled="!isOrderNoEditable">
          <template #append>
            <el-button
              size="small"
              :type="isOrderNoEditable ? 'success' : 'primary'"
              @click="toggleOrderNoEdit"
            >
              {{ isOrderNoEditable ? t('common.done') : t('common.edit') }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item class="w-60%" :label="t('order.signatory')" required>
        <el-input v-model="state.inputDisplayText.signatory" clearable disabled placeholder="">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenSignatory">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('order.signing_date')" class="w-60%" prop="signing_date">
        <el-date-picker
          v-model="form.signing_date"
          type="date"
          :placeholder="t('order.signing_date')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item
        class="w-60%"
        :label="t('order.transfer_payment_info')"
        v-if="form.contract_type == 2"
        :required="form.contract_type == 2"
      >
        <el-select
          v-model="form.transfer_payment_info"
          :placeholder="t('order.transfer_payment_info')"
          @change="handleChangeTransferPaymentInfo"
        >
          <el-option
            v-for="item in transferPaymentInfoList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        class="w-60%"
        :label="state.transfer_payment_info_detail.detail.label"
        v-if="form.transfer_payment_info"
      >
        <el-input
          v-model="state.transfer_payment_info_detail.detail.value"
          type="textarea"
          disabled
          :rows="6"
        />
      </el-form-item>
      <el-form-item
        class="w-60%"
        :label="state.transfer_payment_info_detail.profile.label"
        v-if="form.transfer_payment_info"
      >
        <el-input
          v-model="state.transfer_payment_info_detail.profile.value"
          type="textarea"
          disabled
          :rows="3"
        />
      </el-form-item>

      <el-form-item class="w-60%" :label="t('order.owner')" required>
        <el-input v-model="state.inputDisplayText.owner" clearable disabled placeholder="">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenOwner">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item class="w-60%" :label="t('order.single_order_method')" required>
        <el-select v-model="form.single_order_method" :placeholder="t('order.single_order_method')">
          <el-option
            v-for="item in singleOrderMethodList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="w-60%" :label="t('order.partner')">
        <el-input v-model="state.inputDisplayText.partner" clearable disabled placeholder="">
          <template #append>
            <el-button size="small" text type="success" @click="handleOpenPartner">{{
              t('dealerAssetManagement.select')
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item
        class="w-60%"
        :label="t('order.id_number')"
        prop="id_number"
        :required="form.contract_type == 1 ? true : false"
      >
        <el-input v-model="form.id_number" clearable :placeholder="t('order.id_number')" />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('order.currency')" required>
        <el-select
          v-model="form.currency"
          :placeholder="t('order.currency')"
          @change="handleChangeCurrency"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>
      <!--      商品-->
      <el-form-item class="m-t-20px" :label="t('wholesalOrder.shop')">
        <el-button class="m-l-20px" type="primary" size="small" @click="handleOpenShop"
          >{{ t('wholesalOrder.selectShop') }}
        </el-button>
      </el-form-item>
      <!-- 支付信息列表 -->
      <el-table
        :data="tableList"
        highlight-current-row
        stripe
        border
        show-summary
        :summary-method="getSummaries as any"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          :label="t('wholesalOrder.warehouse')"
          :width="calculateColumnWidth(tableList, 'wid', 2)"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseList, row.wid) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.name')"
          prop="product_name"
          :width="calculateColumnWidth(tableList, 'product_name')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.type')"
          :width="calculateColumnWidth(tableList, 'type')"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(warehouseTypeList, row.is_futures) }}
          </template>
        </el-table-column>

        <el-table-column
          :label="t('wholesalOrder.sellableInventory')"
          :width="calculateColumnWidth(tableList, '', 2)"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ `${row.quantity} ${row.share_id ? '（共享）' : ''}` }}
          </template>
        </el-table-column>

        <el-table-column
          :label="t('wholesalOrder.quantityPurchased')"
          min-width="180"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row, $index }">
            <!-- <el-input-number
              v-model="row!.pay_quantity"
              :min="1"
              :max="row!.quantity ? parseInt(row!.quantity as string) : 100000"
              @change="handleCalcSinglePrice(row, $index)"
            /> -->
            <el-input-number
              v-if="currentRow.pay_status == 3 || currentRow.pay_status == 4"
              v-model="row!.pay_quantity"
              :min="row.allow_zero_stock_sale == 1 ? 0 : 1"
              :max="100000"
              @change="handleCalcSinglePrice(row, $index)"
            />
            <el-input-number
              v-else
              v-model="row!.pay_quantity"
              :min="row.allow_zero_stock_sale == 1 ? 0 : 1"
              :max="
                row.allow_zero_stock_sale == 1
                  ? 100000
                  : row!.quantity
                    ? parseInt(row!.quantity as string)
                    : 100000
              "
              @change="handleCalcSinglePrice(row, $index)"
            />
          </template>
        </el-table-column>

        <el-table-column
          :label="t('wholesalOrder.cost')"
          prop="original_price"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.original_price }}({{ row.actual_quoted_currency_name }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('wholesalOrder.discountedPrice')"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <!-- <el-input v-model="row.actual_price" :clearable="false" placeholder=" " /> -->
            {{ row.actual_price }}({{ row.actual_quoted_currency_name }})
          </template>
        </el-table-column>

        <el-table-column
          :label="
            t('order.actual_selling_price') +
            '[' +
            useEnumeratePicker(currencyList, form.currency) +
            ']'
          "
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <el-input v-model="row.actual_selling_price" :clearable="false" placeholder=" " />
          </template>
        </el-table-column>
        <el-table-column
          label="头程物流费"
          prop="first_leg_logistics_fee"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.code')"
          prop="product_code"
          :width="calculateColumnWidth(tableList, 'product_code')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.computingPower')"
          prop="hashrate"
          :width="calculateColumnWidth(tableList, 'hashrate')"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          :label="t('wholesalOrder.warranty')"
          prop="expiration_date"
          :width="calculateColumnWidth(tableList, 'expiration_date')"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('wholesalOrder.arrivalDate')"
          prop="arrival_date"
          :width="calculateColumnWidth(tableList, 'code')"
          :show-overflow-tooltip="true"
        />

        <el-table-column
          :label="t('wholesalOrder.realArrivalDate')"
          prop="real_arrival_date"
          min-width="86px"
          :show-overflow-tooltip="true"
        />

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ $index }">
            <el-button type="danger" @click="handleDelete($index)" size="small">
              {{ t('wholesalOrder.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      备注-->
      <el-form-item
        :label="t('order.payment_deadline')"
        class="w-60% m-t-20px"
        prop="payment_deadline"
        required
      >
        <el-date-picker
          v-model="form.payment_deadline"
          type="date"
          :placeholder="t('order.payment_deadline')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('order.pay_terms')" required>
        <el-select v-model="form.pay_terms" :placeholder="t('order.pay_terms')">
          <el-option
            v-for="item in payTermsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="w-60%"
        :label="t('wholesalOrder.advance_amount')"
        v-if="form.pay_terms === 1"
      >
        <el-input-number
          class="!w-full"
          v-model="form.advance_amount"
          :min="0"
          :max="form.total_amount ? Number(form.total_amount) : 0"
          required
        />
      </el-form-item>
      <el-form-item class="mobile-item" label="头程物流费">
        <el-input v-model="firstLogisticsFeeTotal" placeholder="" disabled />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('wholesalOrder.total_amount')">
        <el-input v-model="form.total_amount" placeholder="" disabled />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('order.is_sop')">
        <el-checkbox v-model="isSopChecked" @change="handleIsSopChange" />
      </el-form-item>
      <el-form-item class="w-60%" :label="t('wholesalOrder.order_remark')">
        <el-input
          v-model="form.remark"
          type="textarea"
          :autosize="{ minRows: 5, maxRows: 10 }"
          :placeholder="t('wholesalOrder.order_remark')"
        />
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
  <!--  选择客户弹框-->
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />

  <!--  选择签订人弹框-->
  <DialogOperatorChecked
    ref="DialogOperatorCheckedRef"
    @expose-multiple-data="getExposeOperatorData"
  />

  <!--  选择负责人弹框-->
  <DialogOperatorChecked ref="DialogOwnerCheckedRef" @expose-multiple-data="getExposeOwnerData" />

  <!--  选择合伙人弹框-->
  <DialogOperatorChecked
    ref="DialogPartnerCheckedRef"
    :multiple="true"
    @expose-multiple-data="getExposePartnerData"
  />

  <!--  选择商品弹框-->
  <DialogShopChecked ref="DialogShopCheckedRef" @expose-multiple-data="getExposeMultipleData" />
</template>
<script setup lang="ts">
import DialogCustomerChecked from '../../Customer/Customer/components/DialogChecked/index.vue'
// import DialogCustomerChecked from './components/DialogCustomerChecked/index.vue'
import DialogOperatorChecked from '../../Authorization/Operator/components/DialogChecked/index.vue'
import DialogShopChecked from './components/DialogShopChecked/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, ElMessageBox, type FormRules, type FormInstance } from 'element-plus'
import { getSelectApi as getCurrencySelectApi } from '@/api/transactionCurrency'
import {
  getDetailApi,
  editDataApi,
  getInventoryEnumApi,
  getEnumApi as getWholesalOrderEnumApi
} from '@/api/wholesalOrder'
import { hasPowerlineApi } from '@/api/order'
import { oneDimensionalArraySummation, useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { getCurrentDate, formatToDate } from '@/utils/dateUtil'
import Decimal from 'decimal.js'
import { useLocale } from '@/hooks/web/useLocale'
import { useLocaleStore } from '@/store/modules/locale'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
const localeStore = useLocaleStore()

const { t } = useI18n()
const { push, go } = useRouter()

const { query } = useRoute()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const isSopChecked = ref<boolean>(false)
const tableList = ref<any[]>([])
const state = reactive({
  inputDisplayText: {
    signatory: '',
    owner: '',
    partner: ''
  },

  transfer_payment_info_detail: {
    // 付款信息显示数据
    list: [],
    detail: {
      label: '',
      value: ''
    },
    profile: {
      label: '',
      value: ''
    }
  }
})
const form = ref<Record<string, any>>({
  contract_type: 1, //'签署合同类型'
  is_sop: 0, // 是否拼单采购 默认否
  signatory: '',
  order_no: '',
  signing_date: getCurrentDate(),
  single_order_method: 1,
  id_number: '', //统一社会信用代码/身份证号
  payment_deadline: '', //收款截止日期
  transfer_payment_info: '', //付款信息
  contract_signing_status: '', //合同签署状态
  // advance_pay_time: '', // 预付款时间
  currency: 214, // 客户付款币种
  owner: 0,
  partner: '',
  user_id: '',
  username: '',
  email: '',
  remark: ''
})
// 新增：订单编号编辑状态控制
const isOrderNoEditable = ref(false)
const toggleOrderNoEdit = () => {
  isOrderNoEditable.value = !isOrderNoEditable.value
}
const rules = ref<FormRules>({
  signatory: [
    {
      required: true,
      message: t('common.selectText') + t('order.signatory'),
      trigger: 'blur'
    }
  ],
  owner: [
    {
      required: true,
      message: t('common.selectText') + t('order.owner'),
      trigger: 'blur'
    }
  ],
  payment_deadline: [
    {
      required: true,
      message: t('common.selectText') + t('order.payment_deadline'),
      trigger: 'blur'
    }
  ],
  signing_date: [
    {
      required: true,
      message: t('common.selectText') + t('order.signing_date'),
      trigger: 'blur'
    }
  ],
  id_number: [
    {
      required: true,
      message: t('common.inputText') + t('order.id_number'),
      trigger: 'blur'
    }
  ]
})
const DialogCustomerCheckedRef = ref()
const DialogShopCheckedRef = ref()
const DialogOperatorCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 签订人
const DialogOwnerCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 负责人
const DialogPartnerCheckedRef = ref<InstanceType<typeof DialogOperatorChecked>>() // 合伙人

const warehouseList = ref<any[]>([])
const warehouseTypeList = ref<any[]>([])
const contractTypeList = ref<Array<Record<string, any>>>([]) // 签署合同类型下拉数组
const singleOrderMethodList = ref<Array<Record<string, any>>>([]) //成单方式下拉数组
const currencyList = ref<Array<Record<string, any>>>([]) // 客户付款币种下拉数组
const transferPaymentInfoList = ref<Array<Record<string, any>>>([]) // 付款信息下拉数组
const operatorList = ref<Array<Record<string, any>>>([]) // 操作员列表
const payTermsList = ref<Array<Record<string, any>>>([])
// 切换合同类型
const handleChangeContractType = (value: any) => {
  if (1 == value) {
    form.value.transfer_payment_info = ''
  }
}

// 切换付款信息
const handleChangeTransferPaymentInfo = (value: any) => {
  state.transfer_payment_info_detail.list.map((item: any) => {
    if (item.value == value) {
      state.transfer_payment_info_detail.detail.label = item.label.detail_label
      state.transfer_payment_info_detail.detail.value = item.label.detail_value
      state.transfer_payment_info_detail.profile.label = item.label.profile_label
      state.transfer_payment_info_detail.profile.value = item.label.profile_value
    }
  })
}

// 切换客户付款币种
const handleChangeCurrency = (value: any) => {
  tableList.value = []
}

// 处理是否拼单采购复选框变化
const handleIsSopChange = (checked: boolean) => {
  form.value.is_sop = checked ? 1 : 0
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : [],
      'distributor'
    )
  })
}

//打开选择签订人弹框
const handleOpenSignatory = () => {
  nextTick(() => {
    DialogOperatorCheckedRef.value!.dialogVisible = true
    DialogOperatorCheckedRef.value!.initialize(
      form.value.signatory ? [{ id: form.value.signatory }] : []
    )
  })
}

//打开选择负责人弹框
const handleOpenOwner = () => {
  nextTick(() => {
    DialogOwnerCheckedRef.value!.dialogVisible = true
    DialogOwnerCheckedRef.value!.initialize(form.value.owner ? [{ id: form.value.owner }] : [])
  })
}

//打开选择合伙人弹框
const handleOpenPartner = () => {
  nextTick(() => {
    DialogPartnerCheckedRef.value!.dialogVisible = true
    DialogPartnerCheckedRef.value!.initialize(
      form.value.partner
        ? form.value.partner.split(',').map((item) => ({ id: Number(item.trim()) }))
        : []
    )
  })
}

//打开选择商品弹框
const handleOpenShop = () => {
  nextTick(() => {
    DialogShopCheckedRef!.value!.dialogVisible = true
    DialogShopCheckedRef!.value!.initialize(tableList.value, form.value.currency)
  })
}

//计算折扣价格
const handleCalcSinglePrice = (row: Record<string, any>, index: number) => {
  if (row.discount_price && row.discount_price.length) {
    const min = Math.min(...row.discount_price.map((item: any) => item.num))
    const isCurrent = row.discount_price.find((item: any) => item.num === row.pay_quantity)
    const minus = row.discount_price.filter((item: any) => item.num < row.pay_quantity).pop()
    const minusPrice = row.discount_price.reduce(
      (min: Record<string, any>, obj: Record<string, any>) => {
        return min && min.num < obj.num ? min : obj
      },
      row.discount_price[0]
    )

    if (isCurrent) {
      console.log('isCurrent', isCurrent)
      return (
        (tableList.value[index].actual_price = isCurrent.price),
        (tableList.value[index].actual_selling_price = isCurrent.discount_actual_selling_price)
      )
    }
    if (minus) {
      console.log('minus', minus)
      return (
        (tableList.value[index].actual_price = minus.price),
        minus.discount_actual_selling_price &&
          (tableList.value[index].actual_selling_price = minus.discount_actual_selling_price)
      )
    }
    if (row.pay_quantity < min) {
      console.log('minusPrice', minusPrice)
      return (
        (tableList.value[index].actual_price = minusPrice.price),
        minusPrice.discount_actual_selling_price &&
          (tableList.value[index].actual_selling_price = minusPrice.discount_actual_selling_price)
      )
    }
  }
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (!valid) return
    if (!form.value.user_id) return ElMessage.warning('请选择客户')
    if (!form.value.owner) return ElMessage.warning('请选择负责人')
    if (!tableList.value.length) return ElMessage.warning('请选择商品')
    if (!tableList.value.every((item: Record<string, any>) => !!item.actual_price))
      return ElMessage.warning('折扣价格不能为空')

    const params = {
      user_id: form.value.user_id,
      product_list: tableList.value,
      order_remark: form.value.remark,
      contract_type: form.value.contract_type,
      order_no: form.value.order_no,
      signatory: form.value.signatory,
      signing_date: formatToDate(form.value.signing_date) ?? '',
      owner: form.value.owner,
      partner: form.value.partner,
      single_order_method: form.value.single_order_method,
      id_number: form.value.id_number,
      payment_deadline: formatToDate(form.value.payment_deadline) ?? '',
      transfer_payment_info: form.value.transfer_payment_info,
      contract_signing_status: form.value.contract_signing_status,
      currency: form.value.currency,
      pay_terms: form.value.pay_terms,
      advance_amount: form.value.pay_terms == 1 ? form.value.advance_amount : 0,
      first_leg_logistics_fee: firstLogisticsFeeTotal.value,
      is_sop: form.value.is_sop ? 1 : 0
    }
    console.log(params)
    let res = await hasPowerlineApi({
      ids: tableList.value.map((item: any) => item.product_id).join(',')
    })
    if (res.code === 0) {
      if (res.data?.not_powerline?.length > 0 || res.data?.not_powersource?.length > 0) {
        let powerObj = res.data
        let messageHtml = '<div style="padding-bottom: 20px;">'
        if (powerObj?.not_powersource?.length) {
          messageHtml += '<p>以下商品无电源:</p>'
          messageHtml += '<ul style="margin: 10px 0; padding-left: 20px;">'
          // 假设params.list是一个包含商品信息的数组，每个商品有sku, cname等属性
          powerObj.not_powersource.forEach((product: any) => {
            // 检查商品是否有电源线或电源的信息，这里简化为检查是否存在特定属性
            messageHtml += `<li>${product.cname}</li>`
          })
          messageHtml += '</ul>'
        }
        if (powerObj?.not_powerline?.length) {
          messageHtml += '<p>以下商品无电源线:</p>'
          messageHtml += '<ul style="margin: 10px 0; padding-left: 20px;">'
          // 假设params.list是一个包含商品信息的数组，每个商品有sku, cname等属性
          powerObj.not_powerline.forEach((product: any) => {
            // 检查商品是否有电源线或电源的信息，这里简化为检查是否存在特定属性
            messageHtml += `<li>${product.cname}</li>`
          })
          messageHtml += '</ul>'
        }
        messageHtml += '</div>'
        console.log(messageHtml)
        ElMessageBox.confirm(messageHtml, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          customClass: 'msg-wrap'
        }).then(async () => {
          console.log('确定')
          const resp = await editDataApi(parseFloat(query.id as string), params)
          if (resp.code === 0) {
            ElMessage.success('操作成功')
            push('/order/wholesal-order-management')
          }
        })
      } else {
        const resp = await editDataApi(parseFloat(query.id as string), params)
        if (resp.code === 0) {
          ElMessage.success('操作成功')
          push('/order/wholesal-order-management')
        }
      }
    }
  })
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.user_id = val[0].id
  form.value.username = val[0].cusname
  form.value.email = val[0].email
  form.value.owner = val[0].owner_id
  state.inputDisplayText.owner =
    operatorList.value.find((item: any) => item.value === val[0].owner_id)?.label || ''
  val[0].partner = typeof val[0].partner == 'string' ? val[0].partner.split(',') : val[0].partner
  form.value.partner = val[0].partner.join(',')
  state.inputDisplayText.partner = val[0].partner
    .map(
      (partnerId: any) =>
        operatorList.value.find((item: any) => item.value === partnerId)?.label || ''
    )
    .filter((label: string) => label)
    .join(',')
}

//接收勾选中的签订人
const getExposeOperatorData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.signatory && form.value.signatory !== val[0].id) {
  }
  form.value.signatory = val[0].id
  state.inputDisplayText.signatory = val[0].cname
}

//接收勾选中的负责人
const getExposeOwnerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.owner && form.value.owner !== val[0].id) {
  }
  form.value.owner = val[0].id
  state.inputDisplayText.owner = val[0].cname
}

//接收勾选中的合伙人
const getExposePartnerData = (val: any[]) => {
  if (!val || !val.length) return
  if (form.value.partner && form.value.partner !== val[0].id) {
  }
  form.value.partner = val.map((item: any) => item.id).join(',')
  state.inputDisplayText.partner = val.map((item: any) => item.cname).join(',')
}

//接收勾选中的商品
const getExposeMultipleData = (val: any[]) => {
  if (!val || !val.length) return
  const duplicates = tableList.value.map((item: Record<string, any>) => item.unique)
  tableList.value = val.flatMap((item: Record<string, any>) =>
    duplicates.includes(item.unique)
      ? [tableList.value.find((v: Record<string, any>) => item.unique === v.unique) || null]
      : [
          {
            ...item,
            pay_quantity: 1
          }
        ]
  )
}

//列表合计
const firstLogisticsFeeTotal = ref(0)
const getSummaries = (param: Record<string, any>) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  const columnList: number[] = [1, 2, 3]
  columns.forEach((column: Record<string, any>, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
        '合计'
      ])
      return
    }
    if (columnList.includes(index)) {
      sums[index] = h('div', { style: { textAlign: 'center' } }, [])
      return
    }
    if (index === 4) {
      console.log('data', data)
      console.log('sums', sums)
      const values = data.flatMap((item: Record<string, any>) => [item['pay_quantity']])
      console.log('sums[index]', sums[index])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 5) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['original_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 6) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['actual_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 7) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['actual_selling_price'] * item['pay_quantity']
      ])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 8) {
      const values = data.flatMap((item: Record<string, any>) => [
        item['first_leg_logistics_fee'] * item['pay_quantity']
      ])
      firstLogisticsFeeTotal.value = values.reduce((prev: string, curr: string) => {
        return new Decimal(prev ? parseFloat(prev) : 0).add(
          new Decimal(curr ? parseFloat(curr) : 0)
        )
      }, 0)
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${firstLogisticsFeeTotal.value}`
      ])
    }
  })
  return sums
}
//删除某一行
const handleDelete = (index: number) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      tableList.value.splice(index, 1)
    })
    .catch(() => {})
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp_order = await getWholesalOrderEnumApi({ field: 'all' })
  contractTypeList.value = resp_order.data.contract_type
  singleOrderMethodList.value = resp_order.data.single_order_method
  transferPaymentInfoList.value = resp_order.data.transfer_payment_info
  state.transfer_payment_info_detail.list = resp_order.data.transfer_payment_info_detail
  payTermsList.value = resp_order.data.pay_terms
  const Currencyresp = await getCurrencySelectApi({})
  currencyList.value = Currencyresp.data.list

  const resp = await getInventoryEnumApi({ field: 'all' })
  warehouseList.value = resp.data.wid
  warehouseTypeList.value = resp.data.is_futures
  const operatorResp = await getOperatorSelectListApi({})
  operatorList.value = operatorResp.data.list
  await getEcho()
}

//回显
const currentRow = ref<any>({})
const getEcho = async () => {
  const resp = await getDetailApi(parseFloat(query.id as string))
  currentRow.value = resp.data
  console.log('resp.data', resp.data)
  form.value.user_id = resp.data.user_id
  form.value.username = resp.data.user_name
  form.value.order_no = resp.data.order_no
  form.value.email = resp.data.user_email
  form.value.remark = resp.data.order_remark
  form.value.currency = resp.data.currency
  if (resp.data.signatory) {
    form.value.signatory = resp.data.signatory
    state.inputDisplayText.signatory = useEnumeratePicker(operatorList.value, form.value.signatory)
  }

  form.value.id_number = resp.data.id_number
  form.value.payment_deadline = resp.data.payment_deadline
  form.value.contract_type = resp.data.contract_type

  if (resp.data.transfer_payment_info) {
    form.value.transfer_payment_info = parseInt(resp.data.transfer_payment_info)
    handleChangeTransferPaymentInfo(form.value.transfer_payment_info)
  }

  if (resp.data.owner) {
    form.value.owner = resp.data.owner
    state.inputDisplayText.owner = useEnumeratePicker(operatorList.value, form.value.owner)
  }

  if (resp.data.partner) {
    form.value.partner = resp.data.partner
    state.inputDisplayText.partner = resp.data.partner.split(',').map((item) => {
      // 确保每个 item 传入 useEnumeratePicker 时是合法的
      return useEnumeratePicker(operatorList.value, Number(item))
    })
  }

  form.value.pay_terms = resp.data.pay_terms
  form.value.advance_amount = resp.data.advance_amount ? Number(resp.data.advance_amount) : 0
  form.value.is_sop = resp.data.is_sop ? 1 : 0
  isSopChecked.value = form.value.is_sop === 1
  tableList.value = resp.data.products_list
}
onMounted(() => {
  getDropDownBoxInfo()
})
// const currentLang = ref('')
// watch(
//   () => form.value.contract_type,
//   (newVal) => {
//     if (!currentLang.value) {
//       currentLang.value = localeStore.getCurrentLocale.lang
//     }
//     const locale = newVal === 2 ? 'en' : 'zh-CN'
//     const { changeLocale } = useLocale()
//     changeLocale(locale)
//   },
//   {
//     immediate: true
//   }
// )
watchEffect(() => {
  let shopPrice = 0
  if (tableList.value && tableList.value.length) {
    const values = tableList.value.flatMap((item: Record<string, any>) => [
      Number(item['actual_selling_price']) * Number(item['pay_quantity'])
    ])
    shopPrice = values.reduce((acc, val) => acc + val, 0)
  }
  let freight = 0
  form.value.total_amount = shopPrice * 1 + freight * 1 + firstLogisticsFeeTotal.value * 1
  if (form.value.total_amount < form.value.advance_amount) {
    form.value.advance_amount = form.value.total_amount
  }
})
// onUnmounted(() => {
//   // 组件销毁时恢复原来的语言设置
//   if (currentLang.value) {
//     const { changeLocale } = useLocale()
//     changeLocale(currentLang.value as LocaleType)
//     currentLang.value = ''
//   }
// })
// onBeforeRouteLeave(() => {
//   // 组件销毁时恢复原来的语言设置
//   if (currentLang.value) {
//     const { changeLocale } = useLocale()
//     changeLocale(currentLang.value as LocaleType)
//     currentLang.value = ''
//   }
// })
</script>
<style lang="less">
.msg-wrap {
  width: 600px;
  max-width: initial;
}
</style>
